<?php
namespace Core\Datastorage\Tools;

use Core\CoreCommons\Logger as Logger;
use Core;

/**
* ManageDump class definition. This class manage all dump from current database.
*
* @method void ExecuteLastDump()
* @method array GetDumpFileList()
* @method boolean CreateDump()
* @method void CreateEmptyDataBase($databaseName)
* @method void DropDataBase($databaseName)
* @method boolean Backup_Tables($tables = '*')
*/
class ManageDump
{
	/*
	* @property string $dumpRepository The default dump repository
	*/
	private $dumpRepository;

	/*
	* The default constructor
	*/
	public function __construct()
	{
		$this->dumpRepository = DATASTORAGE_DIR. "/dumps/";
		
		if(file_exists($this->dumpRepository) == false)
		{
			mkdir($this->dumpRepository);
		}
	}

	/*
	* Execute the last dump
	*		
	* @todo Get the last dump file instead of use dump.sql
	*/
	public function ExecuteLastDump()
	{
		try
		{
			Logger::Info("Execute last dump");
			
			// Name of the file
			$filename = $this->dumpRepository . 'dump.sql';
			
			$session = Session::Singleton();
			$session->Open();
			
			// Temporary variable, used to store current query
			$templine = '';
			// Read in entire file
			$lines = file($filename);
			// Loop through each line
			foreach ($lines as $line)
			{
				// Skip it if it's a comment
				if (substr($line, 0, 2) == '--' || $line == '')
					continue;
			 
				// Add this line to the current segment
				$templine .= $line;
				// If it has a semicolon at the end, it's the end of the query
				if (substr(trim($line), -1, 1) == ';')
				{
					// Perform the query
					mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
					// Reset temp variable to empty
					$templine = '';
				}
			}
			
			$session->Close();
			
			Logger::Info("Last dump deployed");
		}
		catch(Exception $ex)
		{
			Logger::Error("Execute last dump failed : " . $ex->getMessage());
		}
	}
	
	/*
	* Return the dump files
	*
	* @return array The dump file list
	*/
	public function GetDumpFileList()
	{
		return array_diff(scandir($this->dumpRepository), array('..', '.'));
	}
	
	/*
	* Create a dump of the current database
	*
	* @return boolean Return true if created
	*/
	public function CreateDump()
	{
		try
		{
			Logger::Info("Create dump");
			
			return $this->Backup_Tables();
		}
		catch(Exception $ex)
		{
			CoreCommons\Logger::Error("Create dump failed : " . $ex->getMessage());
		}
	}
	
	/*
	* Create an empty database
	*
	* @param string $databaseName The database name to create
	*/
	public function CreateEmptyDataBase($databaseName)
	{
		try
		{
			Logger::Info("CreateEmptyDataBase : " . $databaseName);
			$session = Core\Datastorage\Session::Singleton();
			$session->Open();

			$sql = 'CREATE DATABASE ' . $databaseName;

			if (mysql_query($sql)) 
			{
				Logger::Info("The database " . $databaseName . " was successfully created");
			} 
			else 
			{
				Logger::Error("Creation " . $databaseName . "failed");
			}
			
			$session->Close();
		}
		catch(Exception $ex)
		{
			Logger::Error("Create dump failed : " . $ex->getMessage());
		}
	}
	
	/*
	* Drop a database
	*
	* @param string $databaseName The database name to drop
	*/
	public function DropDataBase($databaseName)
	{
		try
		{
			Logger::Info("DropDataBase : " . $databaseName);
			$session = Core\Datastorage\Session::Singleton();
			$session->Open();

			$sql = 'DROP DATABASE ' . $databaseName;
			
			if (mysql_query($sql)) 
			{
				Logger::Info("The database " . $databaseName . " was deleted successful");
			} 
			else 
			{
				Logger::Error("Delete " . $databaseName . "failed");
			}
			
			$session->Close();
		}
		catch(Exception $ex)
		{
			Logger::Error("DropDataBase failed : " . $ex->getMessage());
		}
	}
	
	/*
	* Create a backup of the database
	*
	* @param array $tables The tables to backup
	*
	* @return boolean Return true if the backup is created
	*/
	private function Backup_Tables($tables = '*')
	{
		$session = Core\Datastorage\Session::Singleton();
		$session->Open();
		
		//get all of the tables
		if($tables == '*')
		{
			$tables = array();
			$result = mysql_query('SHOW TABLES');
			if(isset($result))
			{
				while($row = mysql_fetch_row($result))
				{
					$tables[] = $row[0];
				}
			}
		}
		else
		{
			$tables = is_array($tables) ? $tables : explode(',',$tables);
		}
		
		$return = '';
		
		//cycle through
		foreach($tables as $table)
		{
			$result = mysql_query('SELECT * FROM '. $table);
			$num_fields = mysql_num_fields($result);
			
			$return .= 'DROP TABLE '. $table . ';';
			$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '. $table));
			$return .= "\n\n".$row2[1].";\n\n";
			
			for ($i = 0; $i < $num_fields; $i++) 
			{
				while($row = mysql_fetch_row($result))
				{
					$return.= 'INSERT INTO '.$table.' VALUES(';
					for($j=0; $j<$num_fields; $j++) 
					{
						$row[$j] = addslashes($row[$j]);
						$row[$j] = preg_replace("/\n/","\\n",$row[$j]);
						if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
						if ($j<($num_fields-1)) { $return.= ','; }
					}
					$return.= ");\n";
				}
			}
			$return.="\n\n\n";
		}
		
		//save file
		$path = $this->dumpRepository . '/dump-'. date("Ymd") .'-'. date("His") .'.sql';

		$handle = fopen($path,'w+');
		fwrite($handle,$return);
		fclose($handle);
		
		$session->Close();
		
		return true;
	}
}

?>